//
//  HMEmoticonToolBar.swift
//  68.新工程-表情键盘_界面搭建
//
//  Created by shenzhenIOS on 16/4/18.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

// 1.定义代理协议
protocol HMEmoticonToolBarDelegate: NSObjectProtocol {
    // 2.定义代理方法
    func emoticonToolBar(toolBar: HMEmoticonToolBar, selectedButtonType type: HMEmoticonToolBarType)
}

// 按钮类型
enum HMEmoticonToolBarType: Int {
    case Recent = 0 // 最近
    case Default = 1 // 默认
    case Emoji = 2  // Emoji
    case Lxh = 3    // 浪小花
}

/// 表情键盘的toolBar,里面管理4个按钮
class HMEmoticonToolBar: UIView {
    
    // 3.定义代理属性
    weak var delegate: HMEmoticonToolBarDelegate?
    
    private var selectedButton: UIButton?

    // 加载xib
    class func emoticonToolBar() -> HMEmoticonToolBar {
        return NSBundle.mainBundle().loadNibNamed("HMEmoticonToolBar", owner: nil, options: nil).last as! HMEmoticonToolBar
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        // 默认选中第0组
        switchSelectButton(0)
    }
    
    @IBAction func didClickButton(sender: UIButton) {
        let type = HMEmoticonToolBarType(rawValue: sender.tag)!
        print("type: \(type)")
        
        switchSelectedButton(sender)
        
        // 4.调用代理
        delegate?.emoticonToolBar(self, selectedButtonType: type)
    }
    
    /// 切换选中按钮通过collecionView的选中section
    func switchSelectButton(section: Int) {
        // 找到对应的按钮
        let button = self.subviews[section] as! UIButton
        
        switchSelectedButton(button)
    }
    
    /// 切换选中按钮
    private func switchSelectedButton(button: UIButton) {
        
        // 如果点击和选中的是同一个按钮,就返回
        if button == selectedButton {
            return
        }
        
        // 1.取消选中的按钮
        selectedButton?.selected = false
        
        // 2.选中当前按钮
        button.selected = true
        
        // 3.将当前按钮赋值给选中按钮
        selectedButton = button
    }
}
